package com.libre.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.libre.auth.entity.Permission;
import com.libre.auth.mapper.PermissionMapper;
import com.libre.auth.service.PermissionService;
import com.libre.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 菜单资源
 * @author 庞留杰
 * @date 2021/12/19 18:59
 * @version V1.0
 **/
@Transactional
@Slf4j
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    public IPage<Permission> findPage(Page initMpPage, Permission permission) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        return this.page(initMpPage, queryWrapper);
    }

    @Override
    public List<Permission> findList(Permission permission) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        List<Permission> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public Permission findById(String id) {
        return this.getById(id);
    }

    @Override
    public boolean add(Permission permission) {
        return this.save(permission);
    }

    @Override
    public boolean update(Permission permission) {
        return this.updateById(permission);
    }

    @Override
    public boolean delete(String id) {
        Permission permission = new Permission();
        permission.setId(id);
        permission.setIsDelete("1");
        return this.updateById(permission);
    }

    @Override
    public List<Permission> menuTree(Permission permission) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("*,CASE is_show WHEN 1 THEN '否' ELSE '是' END isShowName");
        queryWrapper.orderByAsc("sort");
        queryWrapper.eq("is_show", "0");
        queryWrapper.eq("is_delete", "0");
        List<Permission> permissionList = this.list(queryWrapper);
        List<Permission> permissions = iterateMenus(permissionList, "0", permission.getName());
        return permissions;
    }

    /**
     * 多级菜单查询方法
     *
     * @param pid 父类id
     * @return
     */
    public List<Permission> iterateMenus(List<Permission> permissionList, String pid, String resourceName) {
        List<Permission> parents = permissionList.stream().filter(it -> pid.equals(it.getPid())).collect(Collectors.toList());
        Iterator<Permission> iterator = parents.iterator();
        while (iterator.hasNext()) {
            Permission permission = iterator.next();
            if (StringUtil.isNotEmpty(resourceName) && !isSelfAndChildrenByName(permissionList, permission, resourceName)) {
                iterator.remove();//移除
            }
            //获取菜单的id
            String permissionId = permission.getId();
            if (isHasChildren(permissionList, permissionId)) {
                List<Permission> childrens = iterateMenus(permissionList, permissionId, resourceName);
                permission.setChildren(childrens);
            }
        }
        return parents;
    }

    // 判断是否还有子级
    public boolean isHasChildren(List<Permission> permissionList, String id) {
        return permissionList.stream().filter(it -> id.equals(it.getPid())).findFirst().isPresent();
    }

    // 判断自己和子级中是否包含这个部门名称（模糊查询）
    public boolean isSelfAndChildrenByName(List<Permission> permissionList, Permission parent, String resourceName) {
        boolean isContain = parent.getName().contains(resourceName);
        isContain = isChildrenContain(permissionList, parent.getId(), resourceName, isContain);
        return isContain;
    }

    public boolean isChildrenContain(List<Permission> permissionList, String pId, String resourceName, boolean isContain) {
        if (!isContain) {//自己不包含，继续查
            List<Permission> childrens = permissionList.stream().filter(it -> it.getPid().equals(pId)).collect(Collectors.toList());//子级
            for (Permission children : childrens) {
                isContain = children.getName().contains(resourceName);
                if (isContain) {
                    break;
                }
            }
            if (!isContain) {//子级均不包含,继续
                for (Permission children : childrens) {
                    isContain = isChildrenContain(permissionList, children.getId(), resourceName, isContain);
                    if (isContain) {
                        break;
                    }
                }
            }
        }
        return isContain;
    }


}
